<template>
 <el-popover
    v-model="isShow"
    ref="myPopover"
    popper-class="point-select-popover"
    placement="bottom-start"
    transition="el-zoom-in-top"
    trigger="click">
    <el-input  slot="reference" :style="{ width: width + 'px' }" :placeholder="placeholder" ref="input" readonly  
    :clearable="clearable"
    @mouseover.native="mouseover"  @mouseout.native="mouseout"
    style="cursor:pointer" v-model="text">
        <i slot="suffix" class="el-select__caret el-input__icon el-icon-circle-close" v-if="showClearable" @click.stop="clear"></i>
        <i slot="suffix" class="el-select__caret el-input__icon el-icon-arrow-up"  v-else  
        :class="{ 'is-reverse' : isShow}"></i>
    </el-input>
    <el-scrollbar style="height: 300px;" :native="false">  
        <div style="padding: 0px 10px;margin: 5px 0px 0px;">
          <el-input  placeholder="输入关键字进行过滤" prefix-icon="el-icon-search" v-model="filterText" size="mini"></el-input>
        </div>
        <el-tree
          class="filter-tree"
          :data="data"
          node-key="id"
          @node-click="nodeClick"
          @check="check"
          :default-expanded-keys="defaultExpandedKeys"
          :props="defaultProps"
          :accordion="accordion"
          :show-checkbox="showCheckbox"
          :filter-node-method="filterNode"
          ref="tree">
        </el-tree>
        <!--  render-content  default-expand-all-->
   </el-scrollbar>     
</el-popover>
</template>
<script>
export default {
  name: 'PointSelect',
  props: {
    params: {
      type: Object,
      default: () => {
        return {

        };
      }
    },
    clearable: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请选择站点'
    },
    width: {
      type: Number,
      default: 220
    },
    checkAll: { // 是否全选
      type: Boolean,
      default: false
    },
    showCheckbox: { // 是否多选
      type: Boolean,
      default: false
    },
    accordion: { // 是否每次只展开一层
      type: Boolean,
      default: false
    },
    defaultProps: {
      type: Object,
      default: () => {
        return {
          id: 'id',
          children: 'children',
          label: 'text'
        };
      }
    },
    /**
     *@property {String}  autoLoad    - 是否自动加载
     */
    autoLoad: {
      type: Boolean,
      default: true
    },
    checkedKeys: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    checkedKeysAndDataLoad(val) {
      const { checkedKeys, data } = val;
      if (data.length) {
        this.setCheckedKeys(checkedKeys);
      }
    }
    // checkedKeysAndDataLoad: {
    //   handler(val) {
    //     const { checkedKeys, data } = val;
    //     this.$nextTick(_ => {
    //       if (checkedKeys) {
    //         if (!checkedKeys.length) {
    //           this.text = '';
    //           if (this.showCheckbox) {
    //             this.$refs.tree.setCheckedKeys([]);
    //           } else {
    //             this.$refs.tree.setCurrentKey(null);
    //           }
    //         }
    //         if (checkedKeys && data) {
    //           if (checkedKeys.length && data.length) {
    //             this.setCheckedKeys(this.checkedKeys);
    //           }
    //         }
    //       }
    //     });
    //   },
    //   immediate: true
    // }
  },
  computed: {
    checkedKeysAndDataLoad() {
      const { checkedKeys, data } = this;
      return {
        checkedKeys,
        data
      };
    }
  },
  mounted() {
    this.$refs.myPopover.$refs.popper.style.minWidth = this.width + 'px';
  },
  methods: {
    reload() {
      this.getData();
    },
    mouseover() {
      if (this.clearable && this.text) {
        this.showClearable = true;
      } else {
        this.showClearable = false;
      }
    },
    mouseout() {
      this.showClearable = false;
    },
    clear() {
      this.text = '';
      if (this.showCheckbox) {
        this.$refs.tree.setCheckedKeys([]);
        this.$emit('change', []);
      } else {
        this.$refs.tree.setCurrentKey(null);
        this.$emit('change', {});
      }
    },
    resert() {
      this.text = '';
      if (this.showCheckbox) {
        this.$refs.tree.setCheckedKeys([]);
      } else {
        this.$refs.tree.setCurrentKey(null);
      }
    },
    // 设置选中
    setCheckedKeys(checkedKeys) {
      this.$nextTick(_ => {
        this.text = '';
        if (this.showCheckbox) {
          this.$refs.tree.setCheckedKeys([]);
          this.$refs.tree.setCheckedKeys(checkedKeys);
          const checkedNodes = this.$refs.tree.getCheckedNodes();
          const checkedPoints = checkedNodes.filter(v => v.pointid !== undefined);
          if (checkedPoints.length) {
            this.text = checkedPoints.length === 1
              ? checkedPoints[0].text
              : `站点(${checkedPoints.length})`;
          }
          this.$emit('change', checkedPoints);
        } else {
          this.$refs.tree.setCurrentKey(checkedKeys[0]);
          const checkedPoints = this.$refs.tree.getCurrentNode();
          this.text = checkedPoints.text;
          this.$emit('change', checkedPoints);
        }
      });
    },
    // 单选
    nodeClick(a, b, c) {
      if (this.showCheckbox === false) {
        if (b.isLeaf) { // 叶子节点
          this.text = b.data.text;
          this.$emit('change', b.data);
          this.isShow = false;
        }
      }
    },
    // 多选
    check(a, b) {
      if (this.showCheckbox === true) {
        this.text = '';
        const checkedPoints = b.checkedNodes.filter(item => item.pointid !== undefined);
        if (checkedPoints.length) {
          if (checkedPoints.length === 1) {
            this.text = checkedPoints[0].text;
          } else {
            this.text = `站点(${checkedPoints.length})`;
          }
        }
        this.$emit('change', checkedPoints);
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.text.indexOf(value) !== -1;
    },
    getData() {
      this.text = '';
      const httpDataOption = {
        url: '/service-monitor/areaPoint/list',
        type: 'post',
        params: this.params
      };
      this.pointList = [];
      this.$ajax(httpDataOption).then(res => {
        const { success, data } = res;
        if (success) {
          var list = data.data;
          this.data = this.handleData(list);
          this.defaultExpandedKeys = this.pointList.length ? [this.pointList[0].pointid] : [];
          this.$emit('data-load', this.data, this.pointList);
          // if (this.showCheckbox) {
          //   if (this.checkAll) {
          //     const checkedKeys = this.pointList.map(v => v.pointid);
          //     this.setCheckedKeys(checkedKeys);
          //   }
          // }
        }
      });
    },
    getFirstPoint(rows) {
      var point = null;
      const start = list => {
        for (var i = 0; i < list.length; i++) {
          if (list[i].data.length) {
            point = list[i].data[0];
            return;
          }
          if (list[i].children.length) {
            start(list[i].children);
          }
        }
      };
      start(rows);
      return point;
    },
    handleData(list) {
      const start = data => {
        for (var i = 0; i < data.length; i++) {
          if (data[i].pointid === undefined) { // 区域
            data[i].id = data[i].areacode;
            data[i].text = data[i].areaname;
            this.pointList.push(...data[i].data);
            const pointList = data[i].data.map(v => {
              return {
                pointid: v.pointid,
                id: v.pointid,
                text: v.pointname,
                data: v
              };
            });
            data[i].children.unshift(...pointList);
            if (data[i].children && data[i].children.length) {
              start(data[i].children);
            }
          }
        }
      };
      start(list);
      return list;
    }
  },
  data() {
    return {
      id: '',
      text: '',
      isShow: false,
      filterText: '',
      pointList: [],
      data: [],
      defaultExpandedKeys: [],
      showClearable: false
    };
  },
  created() {
    if (this.autoLoad) {
      this.getData();
    }
  }
};
</script>
<style lang="scss">
.point-select-popover{
   padding: 0;
  .popper__arrow{
     left: 35px !important;
  }
}
</style>
<style lang="scss" scoped>
.el-select__caret {
  color: #c0c4cc;
  font-size: 14px;
  transition: transform .3s;
  transform: rotate(180deg);
  cursor: pointer;
}
.el-select__caret.is-reverse {
  transform: rotate(0deg);
}
</style>
